/* eslint-disable no-unused-expressions */
/* eslint-disable no-nested-ternary */
import React, {
  Component,
  useMemo,
  useCallback,
  useState,
  useRef,
  useEffect,
} from "react";

import { notification, message, Dropdown, Menu, Tooltip, Spin } from "hzero-ui";
import styled from "styled-components";
import { Bind } from "lodash-decorators";
import { isNil, isPlainObject, isFunction } from "lodash";
import moment from "moment";
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";
import GanttChart from "tms-front/lib/components/GanttChart";
// import multilingualCode from "tmsCommon/MultilingualCode";

// import beforeDayPNG from "./assets/before-day.png";
// import afterDayPNG from "./assets/after-day.png";

import { computed } from "mobx";
import { observer } from "mobx-react";
import { Icon } from "choerodon-ui";
import { DataSet, Table, DatePicker } from "choerodon-ui/pro";
import { DataSetStatus } from "choerodon-ui/pro/lib/data-set/enum";

import { Button as ButtonPermission } from "components/Permission";
import { Header, Content } from "components/Page";

// import { MacroCode } from "tmsCommon/htms/code/macroCode";

// import { listDS } from './store/indexDS';
// import { queryGanttData } from './api';
// import { handleMacro, handleResponse, isDate } from './utils/utils';
// import { handleGanttDataReceive, findX } from './utils/gantt';

const { Item } = Menu;

type MinuteStepProps = {
  minuteStep: number;
  setMinuteStep: (step: number, cb: Function) => void;
  updateGanttLayout: () => void;
};

function MinuteStep(props: MinuteStepProps) {
  const { minuteStep, setMinuteStep, updateGanttLayout } = props;

  const handleItemClick = useCallback((step: number) => {
    setMinuteStep(step, () => {
      updateGanttLayout();
    });
  }, []);

  const menu = useMemo(() => {
    const items: number[] = [10, 12, 15, 20, 30];
    return (
      <Menu>
        {items.map((item) => (
          <Item
            style={{ padding: "0 8px" }}
            onClick={() => handleItemClick(item)}
          >
            {item}
          </Item>
        ))}
      </Menu>
    );
  }, []);

  return (
    <>
      <Dropdown overlay={menu} placement='bottomRight'>
        <div style={{ float: "right", padding: "0 10px", cursor: "pointer" }}>
          {minuteStep} 分钟/格
        </div>
      </Dropdown>
    </>
  );
}

const Space = styled.div`
  margin-top: 20px;
`;

const GanttDayHeader = styled.div`
  background: transparent;
  height: 25px;
  margin-bottom: -25px;
  position: relative;
  top: 0;
  left: 0;
  z-index: 999;
  float: right;
  width: calc(100% - 300px);
  text-align: center;
  line-height: 25px;
  color: #a6a6a6;

  img {
    width: 14px;
    margin-top: -2px;
    cursor: pointer;
  }

  .before-day {
    margin-right: 6px;
  }

  .after-day {
    margin-left: 6px;
  }
`;

const GanttContainer = styled.div`
  height: 292px;
  user-select: none;

  .gantt-grid-head-cell {
    border-right: 1px solid #ebebeb !important;
  }

  .enable-task {
    background: #2c6ffe;
    border: 2px solid #2c6ffe;

    :global {
      .gantt_task_content {
        text-overflow: ellipsis;
      }
    }
  }

  .disable-task {
    background: #6b6b6b;
    border: 2px solid #6b6b6b;

    &:hover {
      cursor: not-allowed;
    }

    :global {
      .gantt_task_content {
        cursor: not-allowed;
        text-overflow: ellipsis;
      }
    }
  }

  .selected-task {
    border: 2px solid #07e2f3;
    background: #0ebdef;
  }
`;

const RailwayGantt = (props: {
  minuteStep: any;
  setMinuteStep: any;
  setSelectedTask: any;
  data: any;
}) => {
  const container = useRef(null);
  const [ganttDateValue, setGanttDateValue] = useState(
    new Date(moment().format("YYYY-MM-DD 00:00:00")).valueOf(),
  );

  const { minuteStep, setMinuteStep, setSelectedTask, data } = props;
  // HTMSGanttChartFactory为甘特图组件暴露的方法
  const gantt = useMemo(() => HTMSGanttChartFactory().gantt, []);

  useEffect(() => {
    initGannt();
  }, [gantt, container]);

  const initGannt = () => {
    if (!container?.current) return;
    if (!gantt) return;

    gantt.plugins({
      tooltip: true,
    });
    gantt.config.columns = [
      {
        name: "locationName",
        label: "仓库名称",
        tree: false,
        align: "center",
        resize: true,
        width: 150,
      },
      {
        name: "dockName",
        label: "月台名称",
        tree: false,
        align: "center",
        resize: true,
        width: 150,
      },
    ];
    gantt.templates.grid_header_class = (columnName) => {
      if (columnName === "locationName") {
        return "gantt-grid-head-cell";
      }
    };
    setGanttScales();
    gantt.config.scale_height = 75;
    gantt.config.min_column_width = 20;
    gantt.config.readonly = true;
    gantt.config.date_format = "%Y-%m-%d %H:%i";
    gantt.config.duration_unit = "minute";
    gantt.config.duration_step = 1;
    gantt.config.row_height = 40;
    gantt.config.task_height = 30;
    gantt.templates.task_class = (start, end, task) => {
      const { enable, isSelected } = task;
      return enable
        ? isSelected
          ? "enable-task selected-task"
          : "enable-task"
        : "disable-task";
    };
    gantt.templates.task_text = (start, end, task) => {
      const { enable, dimension, count, parentEnable } = task;
      return !parentEnable
        ? "不可用"
        : enable
        ? `可预约${isNil(dimension) ? "-" : dimension}：${
            isNil(count) ? "-" : count
          }`
        : "已约满";
    };
    gantt.templates.tooltip_text = (start, end, task) => {
      const { $level, enable, dimension, count, parentEnable } = task;
      if ($level !== 0) {
        return `<div style="background:black;
            color:white;
            padding:6px;
            margin:-11px;
            border: 1px solid black;
            opacity: 0.8;">
              ${
                !parentEnable
                  ? "不可用"
                  : enable
                  ? `可预约${isNil(dimension) ? "-" : dimension}：${
                      isNil(count) ? "-" : count
                    }`
                  : "已约满"
              }
            </div>`;
      }
    };
    gantt.attachEvent("onTaskUnselected", (id) => {
      if (gantt.isTaskExists(id)) {
        const task = gantt.getTask(id);
        const { enable, $level } = task;
        if ($level !== 0 && enable) {
          task.isSelected = false;
          gantt.updateTask(id);
        }
      }
    });
    gantt.attachEvent("onTaskClick", (id) => {
      const task = gantt.getTask(id);
      const { enable, $level, isSelected } = task;
      if ($level !== 0 && enable) {
        const { setSelectedTask } = props;
        if (isSelected) {
          task.isSelected = false;
          setSelectedTask?.(null);
          message.info("时间窗已取消。");
        } else {
          task.isSelected = true;
          setSelectedTask?.(task);
          message.success("时间窗已选中。");
        }
        gantt.updateTask(id);
      }
      return $level !== 0 && enable;
    });
    gantt.attachEvent("onGanttReady", () => {
      const { tooltips } = gantt.ext;
      tooltips.tooltip.setViewport(gantt.$task_data);
      gantt.scrollTo(0, 0);
    });
    // 初始化
    gantt.init(
      container.current,
      new Date(moment().format("YYYY-MM-DD 00:00:00")),
      new Date(moment().format("YYYY-MM-DD 23:59:59")),
    );
    gantt.parse({
      data: props.data,
    });
  };

  const setGanttScales = () => {
    const { minuteStep } = props;
    gantt.config.scales = [
      {
        unit: "day",
        format: formatHeader,
      },
      {
        unit: "hour",
        format: "%G %a",
      },
      {
        unit: "minute",
        step: minuteStep,
        format: "%i",
      },
    ];
  };

  const formatHeader = () => {
    return "";
  };

  const title = moment(ganttDateValue).format("MM/DD/YYYY");

  return (
    <>
      {/* <div className={styles.space} /> */}
      <Space />
      <GanttDayHeader>
        <img src={""} alt='前一天' className='before-day' onClick={() => {}} />
        {title}
        <img src={""} alt='后一天' className='after-day' onClick={() => {}} />
        <MinuteStep
          minuteStep={minuteStep}
          setMinuteStep={setMinuteStep}
          updateGanttLayout={() => {
            console.log("更新甘特图");
          }}
        />
      </GanttDayHeader>
      <GanttContainer ref={container} onMouseLeave={() => {}} />
    </>
  );
};

// class App extends Component {
//   constructor(props) {
//     super(props);

//     this.state = {
//       submitLoading: false,
//       cancelLoading: false,
//       // 甘特图被选中的任务
//       selectedTask: null,
//       // 甘特图数据
//       ganttData: [],
//       spinning: false,
//       // 被选中的行id
//       selectedRowId: null,
//       // 分钟步长
//       minuteStep: 20,
//     };

//     this.tableDS = new DataSet(listDS(this));
//     this.gantt = null;
//   }

//   @Bind
//   queryGanttData() {
//     const { minuteStep } = this.state;
//     const { selected } = this.tableDS;
//     if (selected && selected.length) {
//       const record = selected[0];
//       this.setState({ spinning: true });
//       const param = {
//         locationGid: record.get("locationGid"),
//         ganttDate: `${this.gantt?.getGanttDate()} 00:00:00`,
//         id: record.get("id"),
//       };
//       queryGanttData(param)
//         .then((response) => {
//           handleResponse(
//             response,
//             (data) => {
//               const ganttData = handleGanttDataReceive(
//                 data,
//                 this.gantt?.getGanttDate(),
//                 {
//                   stopType: record.get("stopType"),
//                 },
//               );
//               const x = findX(data, minuteStep);
//               this.setState(
//                 {
//                   ganttData,
//                 },
//                 () => {
//                   this.gantt?.updateGantt(x);
//                 },
//               );
//             },
//             () => {
//               this.setState(
//                 {
//                   ganttData: [],
//                 },
//                 () => {
//                   this.gantt?.updateGantt(0);
//                 },
//               );
//             },
//           );
//         })
//         .finally(() => {
//           this.setState({ spinning: false });
//         });
//     } else {
//       this.gantt?.clearAll();
//     }
//   }

//   @Bind
//   setSelectedTask(task) {
//     this.setState({
//       selectedTask: task,
//     });
//   }

//   setMinuteStep = (step, cb) => {
//     this.setState(
//       {
//         minuteStep: step,
//       },
//       () => {
//         if (isFunction(cb)) {
//           cb();
//         }
//       },
//     );
//   };

//   render() {
//     const { ganttData, minuteStep, spinning } = this.state;
//     return (
//       <>
//         <Spin spinning={spinning} tip='Loading...'>
//           <RailwayGantt
//             data={ganttData}
//             setSelectedTask={this.setSelectedTask}
//             ref={(gantt) => {
//               this.gantt = gantt;
//             }}
//             queryGanttData={this.queryGanttData}
//             minuteStep={minuteStep}
//             setMinuteStep={this.setMinuteStep}
//           />
//         </Spin>
//       </>
//     );
//   }
// }

// class App extends Component {
//   render() {
//     return null;
//   }
// }

// 测试 MinuteStep 组件
// const App = () => {
//   const [minuteStep, setMinuteStep] = useState(10);

//   return (
//     <>
//       <MinuteStep
//         minuteStep={minuteStep}
//         setMinuteStep={setMinuteStep}
//         updateGanttLayout={() => {
//           console.log("更新甘特图");
//         }}
//       />
//     </>
//   );
// };

// 测试 RailwayGantt组件

// const App = () => {
//   const [minuteStep, setMinuteStep] = useState(10);

//   const data = [
//     {
//       id: "1",
//       render: "split",
//       start_date: "2022-12-16 00:00",
//       end_date: "2022-12-16 00:00",
//       duration: 0,
//       isSelected: false,
//       locationName: "北京仓库RDC",
//       locationGid: 59500,
//       dockName: "北京仓库月台A",
//       dockGid: 4,
//       enable: true,
//     },
//     {
//       parent: "1",
//       id: "1.1",
//       dimension: "重量",
//       count: 1000,
//       locationGid: 59500,
//       dockGid: 4,
//       dockResourceLineGid: 2,
//       isSelected: false,
//       parentEnable: true,
//       enable: true,
//       start_date: "2022-12-16 13:00",
//       end_date: "2022-12-16 19:00",
//       appointmentDate: "2022-12-16 00:00:00",
//     },
//     {
//       parent: "1",
//       id: "1.2",
//       dimension: "重量",
//       count: 1000,
//       locationGid: 59500,
//       dockGid: 4,
//       dockResourceLineGid: 1,
//       isSelected: false,
//       parentEnable: true,
//       enable: true,
//       start_date: "2022-12-16 08:00",
//       end_date: "2022-12-16 12:00",
//       appointmentDate: "2022-12-16 00:00:00",
//     },
//   ];

//   return (
//     <>
//       <RailwayGantt
//         minuteStep={minuteStep}
//         setMinuteStep={setMinuteStep}
//         setSelectedTask={() => {
//           console.log("选择任务");
//         }}
//         data={data}
//       />
//     </>
//   );
// };

const ComponentWrapper = styled.div`
  width: 1200px;
`;

const App = (props) => {
  const [minuteStep, setMinuteStep] = useState(10);

  const data = [
    {
      id: "1",
      render: "split",
      start_date: "2022-12-16 00:00",
      end_date: "2022-12-16 00:00",
      duration: 0,
      isSelected: false,
      locationName: "北京仓库RDC",
      locationGid: 59500,
      dockName: "北京仓库月台A",
      dockGid: 4,
      enable: true,
    },
    {
      parent: "1",
      id: "1.1",
      dimension: "重量",
      count: 1000,
      locationGid: 59500,
      dockGid: 4,
      dockResourceLineGid: 2,
      isSelected: false,
      parentEnable: true,
      enable: true,
      start_date: "2022-12-16 13:00",
      end_date: "2022-12-16 19:00",
      appointmentDate: "2022-12-16 00:00:00",
    },
    {
      parent: "1",
      id: "1.2",
      dimension: "重量",
      count: 1000,
      locationGid: 59500,
      dockGid: 4,
      dockResourceLineGid: 1,
      isSelected: false,
      parentEnable: true,
      enable: true,
      start_date: "2022-12-16 08:00",
      end_date: "2022-12-16 12:00",
      appointmentDate: "2022-12-16 00:00:00",
    },
  ];

  return (
    <>
      <ComponentWrapper>
        <RailwayGantt
          minuteStep={minuteStep}
          setMinuteStep={setMinuteStep}
          setSelectedTask={() => {
            console.log("选择任务");
          }}
          data={data}
        />
      </ComponentWrapper>
    </>
  );
};

export default App;
